﻿CREATE Procedure [dbo].[sec_AddNewLoan]
@CompanyID int = 0,
@StatusID int = 0
As
IF @CompanyID IS NULL SET @CompanyID = 0

DECLARE @LoanID int
IF ISNULL(@StatusID,0) = 0 SET @StatusID = dbo.fs_StateID_Start('t_Loan');

DECLARE @ContractHolderID int SET @ContractHolderID = dbo.IsContractHolder()

SELECT @LoanID = fsa.LoanID FROM  
t_Loan L
INNER JOIN t_CarInfo ci ON L.ID = ci.LoanID
INNER JOIN v_Borrower_0 t_Borrower ON L.ID = t_Borrower.LoanID
CROSS APPLY fs_Loans_Read(L.ID, DEFAULT)fsa
WHERE L.CompanyID = @CompanyID AND
			(L.StatusID = @StatusID) AND
			(ISNULL(FirstName,'') = '') AND
			(ISNULL(LastName,'') = '') AND
			(ISNULL(SSN,'') = '') AND
      (DATEDIFF(dd, StatusDate, GETDATE())<7) AND
			ISNULL(ci.VIN,'') = ''

IF @LoanID IS NULL OR
	 dbo.PageCount(@LoanID,DEFAULT) > 0 BEGIN
	INSERT t_Loan(CompanyID,StatusID)VALUES(@CompanyID,@StatusID)
	SET @LoanID = IDENT_CURRENT('t_Loan')
END

IF ISNULL(@ContractHolderID,0) > 0
	UPDATE t_Loan SET ContractHolderID = @ContractHolderID WHERE ID = @LoanID

RETURN @LoanID


